/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * A utility class for applying XSLT transforms to XML documents. Initial uses
 * are applying abbreviate and html transforms to XML renderings of Alloy
 * solutions.
 * 
 * @author drayside
 */
public class XSLT {

    private static final String ABBREVIATE = "solution-abbreviate.xslt";

    private static final String HTML = "solution-html.xslt";

    /**
     * Simple unit tests.
     * 
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        /*
        InputStream s = XSLT.class.getResourceAsStream(HTML);
        BufferedReader r = new BufferedReader(new InputStreamReader(s));
        String line;
        while ((line = r.readLine()) != null)
            System.out.println(line);
        */
        System.out.println(htmlSolution("<solution> <module name='m'> <sig name='s'/> </module> </solution>"));
        System.out.println();
        System.out.println(abbreviateSolution("<solution> <module name='m'> <sig name='s'/> </module> </solution>"));
    }

    /**
     * 
     * @param xmlString XML rendering of an Alloy instance
     * @return abbreviated XML rendering of the instance
     */
    public static String abbreviateSolution(final String xmlString) {
        return transform(xmlString, ABBREVIATE);
    }

    public static String htmlSolution(final String xmlString) {
        return transform(xmlString, HTML);
    }

    public static String transform(final String xmlString, final String xsltResource) {
        return transform(xmlString, new StreamSource(
                new InputStreamReader(XSLT.class.getResourceAsStream(xsltResource))));
    }

    public static String transform(final String xmlString, final Source xsltReader) {

        try {
            //Get a factory object for DocumentBuilder
            // objects with default configuration.
            final DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();

            //Get a DocumentBuilder (parser) object
            final DocumentBuilder parser = docBuildFactory.newDocumentBuilder();

            //Parse the XML input file to create a
            // Document object that represents the
            // input XML file.
            final Document document = parser.parse(new InputSource(
					new java.io.StringReader(xmlString)));


            //Get a TransformerFactory object
            final TransformerFactory xformFactory = TransformerFactory.newInstance();
            //Get an XSL Transformer object
            final Transformer transformer = xformFactory.newTransformer(xsltReader);
            //Get a DOMSource object that represents
            // the Document object
            final DOMSource source = new DOMSource(document);

            // finally do the transformation ...
            final StringWriter w = new StringWriter();
            transformer.transform(source, new StreamResult(w));
            return w.toString();
            
        }//end try block

        catch (SAXParseException saxEx) {
            System.err.println("\nSAXParseException");
            System.err.println("Public ID: " + saxEx.getPublicId());
            System.err.println("System ID: " + saxEx.getSystemId());
            System.err.println("Line: " + saxEx.getLineNumber());
            System.err.println("Column:" + saxEx.getColumnNumber());
            System.err.println(saxEx.getMessage());

            Exception ex = saxEx;
            if (saxEx.getException() != null) {
                ex = saxEx.getException();
                System.err.println(ex.getMessage());
            }
        }//end catch

        catch (SAXException saxEx) {
            //This catch block may not be reachable.
            System.err.println("\nParser Error");
            System.err.println(saxEx.getMessage());

            Exception ex = saxEx;
            if (saxEx.getException() != null) {
                ex = saxEx.getException();
                System.err.println(ex.getMessage());
            }
        }//end catch

        catch (ParserConfigurationException parConEx) {
            System.err.println("\nParser Config Error");
            System.err.println(parConEx.getMessage());
        }//end catch

        catch (TransformerConfigurationException transConEx) {
            System.err.println("\nTransformer Config Error");
            System.err.println(transConEx.getMessage());

            Throwable ex = transConEx;
            if (transConEx.getException() != null) {
                ex = transConEx.getException();
                System.err.println(ex.getMessage());
            }
        }//end catch

        catch (TransformerException transEx) {
            System.err.println("\nTransformation error");
            System.err.println(transEx.getMessage());

            Throwable ex = transEx;
            if (transEx.getException() != null) {
                ex = transEx.getException();
                System.err.println(ex.getMessage());
            }
        }//end catch}

        catch (Exception e) {
            e.printStackTrace(System.err);
        }//end catch

        return "an exception occurred while trying to run the XSLT processor; see system console for details";
    }
}